package com.zw.yzk.kabu.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.zw.yzk.kabu.R;
import com.zw.yzk.kabu.adapter.GoodsOrderGoodsAdapter;
import com.zw.yzk.kabu.base.BaseActivity;
import com.zw.yzk.kabu.constant.ActivityConstant;
import com.zw.yzk.kabu.data.network.task.GoodsOrderTask;
import com.zw.yzk.kabu.domain.interactor.DefaultOnNext;
import com.zw.yzk.kabu.internal.component.DaggerGoodsOrderDetailsComponent;
import com.zw.yzk.kabu.internal.module.ActivityModule;
import com.zw.yzk.kabu.internal.module.GoodsOrderDetailsModule;
import com.zw.yzk.kabu.management.LoadingDialogManager;
import com.zw.yzk.kabu.management.ToastManager;
import com.zw.yzk.kabu.management.ToolbarBuilder;
import com.zw.yzk.kabu.model.GoodsOrderDetailsModel;
import com.zw.yzk.kabu.model.GoodsOrderModel;
import com.zw.yzk.kabu.presenter.GoodsOrderDetailsPresenter;
import com.zw.yzk.kabu.utils.ResUtils;
import com.zw.yzk.kabu.view.view.GoodsOrderDetailsView;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.OnClick;
import rx.Observable;

/**
 * Created by zhanwei on 2017/2/9.
 */

public class GoodsOrderDetailsActivity extends BaseActivity implements GoodsOrderDetailsView {

    @Bind(R.id.name)
    TextView name;
    @Bind(R.id.phone)
    TextView phone;
    @Bind(R.id.address)
    TextView address;
    @Bind(R.id.shop_name)
    TextView shopName;
    @Bind(R.id.order_state)
    TextView orderState;
    @Bind(R.id.goods_count)
    TextView goodsCount;
    @Bind(R.id.total_price)
    TextView totalPrice;
    @Bind(R.id.goods_list)
    RecyclerView goodsList;
    @Bind(R.id.order_id)
    TextView orderId;
    @Bind(R.id.create_time)
    TextView createTime;
    @Bind(R.id.wechat_order)
    TextView wechatOrder;
    @Bind(R.id.layout_pending_payment)
    View pendingPayment;
    @Bind(R.id.layout_pending_deliver)
    View pendingDeliver;
    @Bind(R.id.layout_pending_receive)
    View pendingReceive;
    @Bind(R.id.layout_complete)
    View complete;
    @Bind(R.id.layout_cancel_order)
    View cancel;
    @Bind(R.id.freight)
    TextView freight;

    @Inject
    GoodsOrderDetailsPresenter presenter;
    private GoodsOrderGoodsAdapter adapter;
    private String logisticId;
    private String orderIdStr;

    @Override
    public int getLayoutId() {
        return R.layout.activity_goods_order_paid_details;
    }

    @Override
    public void iniToolbar(BaseActivity activity) {
        ToolbarBuilder
                .createBuilder(this)
                .setTitle(getResources().getString(R.string.goods_order_details))
                .build();
    }

    @Override
    public void initComponent() {
        DaggerGoodsOrderDetailsComponent.builder()
                .applicationComponent(getApplicationComponent())
                .activityModule(new ActivityModule(this))
                .goodsOrderDetailsModule(new GoodsOrderDetailsModule())
                .build()
                .inject(this);
        presenter.setView(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initRecyclerView();
        getGoodsOrderDetails();
        LoadingDialogManager.getInstance().showLoadingDialog(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkTradeStatus();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter != null) {
            presenter.destroy();
        }
    }

    @Override
    public void getGoodsOrderDetailsSuccess(GoodsOrderDetailsModel model) {
        logisticId = model.getLogisticId();
        orderIdStr = model.getOrderId();

        shopName.setText(model.getShopName());
        name.setText(model.getReceiveName());
        phone.setText(model.getReceivePhone());
        address.setText(model.getReceiverAddress());
        orderState.setText(model.getOrderTypeStr());
        goodsCount.setText(getResources().getString(R.string.order_goods_count, model.getGoodsCount()));
        totalPrice.setText(ResUtils.formatCurrency(this, model.getTotalPrice()));
        orderId.setText(getResources().getString(R.string.ticket_order_id, model.getOrderId()));
        createTime.setText(getResources().getString(R.string.ticket_create_time, model.getOrderId()));
        wechatOrder.setText(getResources().getString(R.string.wx_trade_id, model.getOrderId()));
        filterOrderAction(model.getOrderType());

        String freightCount = "(含运费" + ResUtils.formatCurrency(this, model.getFreight()) + ")";
        freight.setText(freightCount);

        if (adapter == null) {
            adapter = new GoodsOrderGoodsAdapter(model.getGoodsList());
            goodsList.setAdapter(adapter);
        } else {
            adapter.refresh(model.getGoodsList());
        }
    }

    @Override
    public void receiveSuccess() {
        ToastManager.getInstance().showToast(this, getResources().getString(R.string.confirm_receive_success));
        Observable.timer(500, TimeUnit.MILLISECONDS)
                .subscribe(new DefaultOnNext<Long>() {
                    @Override
                    public void call(Long var1) {
                        finish();
                    }
                });
    }

    @Override
    public void queryOrderStateSuccess() {
        ToastManager.getInstance().showToast(this, getResources().getString(R.string.paid_success));
        startActivity(new Intent(this, MyGoodsOrderActivity.class));
        finish();
    }

    @OnClick(R.id.pay)
    public void pay() {
        LoadingDialogManager.getInstance().showLoadingDialog(this);
        payOrder(orderIdStr);
    }

    @OnClick(R.id.urge)
    public void urge() {
        new AlertDialog.Builder(this)
                .setCancelable(true)
                .setMessage(R.string.urge_oder)
                .setPositiveButton(R.string.confirm, null)
                .show();
    }

    @OnClick(R.id.view_logistics_pending)
    public void pLogistics() {
        Intent intent = new Intent(this, LogisticsActivity.class);
        intent.putExtra(ActivityConstant.LOGISTICS_ID, logisticId);
        startActivity(intent);
    }

    @OnClick(R.id.view_logistics_complete)
    public void cLogistics() {
        Intent intent = new Intent(this, LogisticsActivity.class);
        intent.putExtra(ActivityConstant.LOGISTICS_ID, logisticId);
        startActivity(intent);
    }

    @OnClick(R.id.confirm_receive)
    public void confirmReceive() {
        LoadingDialogManager.getInstance().showLoadingDialog(this);
        confirmReceive(orderIdStr);
    }

    @OnClick(R.id.apply_cancel)
    public void applyCancel() {
        Intent intent = new Intent(this, RefundActivity.class);
        intent.putExtra(ActivityConstant.REFUND_ORDER_ID, orderIdStr);
        startActivity(intent);
    }

    /**
     * 初始化RecyclerView
     */
    private void initRecyclerView() {
        goodsList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        goodsList.setNestedScrollingEnabled(false);
    }

    /**
     * 筛选需要显示的操作按钮
     */
    private void filterOrderAction(int orderType) {
        pendingPayment.setVisibility(View.GONE);
        pendingDeliver.setVisibility(View.GONE);
        pendingReceive.setVisibility(View.GONE);
        complete.setVisibility(View.GONE);
        cancel.setVisibility(View.GONE);
        switch (orderType) {
            case GoodsOrderTask.GOODS_ORDER_COMPLETE:
                complete.setVisibility(View.VISIBLE);
                break;
            case GoodsOrderTask.GOODS_ORDER_UNDELIVER:
                pendingDeliver.setVisibility(View.VISIBLE);
                break;
            case GoodsOrderTask.GOODS_ORDER_UNPAIED:
                pendingPayment.setVisibility(View.VISIBLE);
                break;
            case GoodsOrderTask.GOODS_ORDER_UNRECEIVE:
                pendingReceive.setVisibility(View.VISIBLE);
                break;
            case GoodsOrderTask.GOODS_ORDER_BACK:
                break;
        }
    }

    /**
     * 获取订单详情
     */
    private void getGoodsOrderDetails() {
        presenter.getGoodsOrderDetails(getIntent().getStringExtra(ActivityConstant.GOODS_ORDER_DETAILS_ID),
                getIntent().getIntExtra(ActivityConstant.GOODS_ORDER_DETAILS_TYPE, -1));
    }

    /**
     * 付款
     *
     * @param orderId
     */
    private void payOrder(String orderId) {
        presenter.pay(orderId);
    }

    /**
     * 确认订单
     *
     * @param orderId 订单id
     */
    private void confirmReceive(String orderId) {
        presenter.confirmReceive(orderId);
    }

    /**
     * 查询订单状态
     */
    public void checkTradeStatus() {
        presenter.checkOrderState();
    }
}
